import datetime
import json

from django import http
from django.core.paginator import Paginator
from django.shortcuts import render
from django.views import View

from apps.address.models import Area
from apps.house.models import House, Facility, HouseImage
from apps.order.models import Order
from apps.users.models import User
from love_home.settings.dev import logger
from love_home.utils.qiniuyun import upload_img
from love_home.utils.response_code import RET
from love_home.utils.views import LoginRequiredJSONMixin


class HouseDetailView(LoginRequiredJSONMixin, View):
    def get(self, request, house_id):
        # 校验参数
        try:
            house = House.objects.get(pk=house_id)
        except Exception as e:
            print(e)
            return http.JsonResponse({'errno': RET.DBERR, 'errmsg': '数据库查询错误'})
        # 业务逻辑
        # 创建一个大字典 大字典里包房屋信息 房屋图片列表 房屋设置列表 以及评论列表嵌套字典
        house_dict = {
            'acreage': house.acreage,  # int	房屋面积
            'title': house.title,  # str	标题
            'price': house.price,  # str	价格
            'area_id': house.area.pk,  # int	城区id
            'address': house.address,  # str	房屋地址
            'room_count': house.room_count,  # int	房间数目
            'unit': house.unit,  # str	房屋单元，如：几室几厅
            'capacity': house.capacity,  # int	房屋容纳的人数
            'beds': house.beds,  # str	房屋床铺的配置
            'deposit': house.deposit,  # str	房屋押金
            'min_days': house.min_days,  # int	最少入住天数
            'max_days': house.max_days,  # int	最大入住天数，0表示不限制
            'hid': house.id,  # int	房屋ID
            'user_avatar': house.user.avatar_url,  # str	该房屋所有者的头像
            'user_id': house.user.pk,  # str	该房屋所有者的用户id
            'user_name': house.user.username,  # str  该房屋所有者的昵称
        }
        # 房屋设施信息列表
        facilities = [i.id for i in house.facilities.all()]
        house_dict['facilities'] = facilities
        # 房屋图片列表
        img_urls = [i.url for i in house.houseimage_set.all()]
        house_dict['img_urls'] = img_urls
        # 评论列表
        comments = []
        order = Order.objects.filter(house=house)
        for i in order:
            comments.append({
                'comment': i.comment,
                'user_name': i.user.username,
                'ctime': i.update_time.strftime('%Y-%m-%d-%H:%M:%S')
            })
        house_dict['comments'] = comments
        # 组建前端数据格式
        data = {
            'user_id': request.user.pk,
            'house': house_dict
        }
        # 返回响应内容
        return http.JsonResponse({'errno': RET.OK, 'errmsg': 'ok', 'data': data})

# 房屋首页
class HouseIndexView(View):
    def get(self, request):
        # 查询所有房源信息 并按照订单数量降虚排列
        try:
            houses = House.objects.all().order_by('-order_count')
        except Exception as e:
            print(e)
            return http.JsonResponse({'errno': RET.DBERR, 'errmsg': '数据库查询错误'})
        # 判断数量
        if houses.count() > 3:
            houses = houses[:3]
        # 创建空列表
        houses_list = []
        for house in houses:
            houses_list.append({
                'house_id': house.pk,
                'img_url': house.index_image_url,
                'title': house.title,
            })
        # 返回响应对象
        return http.JsonResponse({'errno': RET.OK, 'errmsg': 'ok', 'data': houses_list})


# 房屋搜索
class HouseSearchView(LoginRequiredJSONMixin, View):
    def get(self, request):
        # 接收参数
        area_id = request.GET.get('aid')  # 城区id
        start_date = request.GET.get('sd') # 开始时间
        end_date = request.GET.get('ed') # 结束时间
        sk = request.GET.get('sk')  # 排序方式
        p = request.GET.get('p', 1) # 页数
        # 转换日期格式
        house_ids_order = []
        if start_date and end_date:
            # 将前端传过来的时间转换成datetime数据格式
            date_start = datetime.datetime.strptime(start_date, '%Y-%m-%d')
            date_end = datetime.datetime.strptime(end_date, '%Y-%m-%d')
            # 判断时间 转换格式
            if date_start > date_end:
                return http.JsonResponse({'errno': RET.PARAMERR, 'errmsg': "参数错误"})
            # 取出数据库里结束时间大于前端传过来的开始时间的所有订单
            orders = Order.objects.filter(end_date__gte=date_start)
            # 根据取出来的订单取出house_id
            for order in orders:
                house_ids_order.append(order.house.pk)
        # 判断城区id
        if area_id:
            houses = House.objects.filter(area_id=area_id)
            houses = houses.exclude(id__in=house_ids_order)
        else:
            houses = House.objects.all()
            houses = houses.exclude(id__in=house_ids_order)
        # 判断排序条件
        if sk == 'booking':  # 订单销量排序(入住最多)
            houses = houses.order_by('-order_count')
        elif sk == 'price-inc':  # 价格由低到高排序
            houses = houses.order_by('price')
        elif sk == 'price-des':  # 价格由高到低排序
            houses = houses.order_by('-price')
        else:
            houses = houses.order_by('create_time')  # 按时间排序(最新创建)
        # 转换页数格式
        try:
            p = int(p)
        except Exception as e:
            print(e)
            return http.JsonResponse({'errno': RET.PARAMERR, 'errmsg': "参数错误"})
        # 创建分页器对象
        paginator = Paginator(houses, 2)
        # 获取总页数
        num_pages = paginator.num_pages
        # 获取指定页数的数据
        page = paginator.page(p)
        # 构建房屋数据格式
        houses_list = []
        for house in page:
            houses_list.append({
                'house_id': house.pk,  # 房屋id
                'order_count': house.order_count,  # 房租入住数量
                'title': house.title,  # 房屋标题
                'ctime': house.create_time.strftime('%Y-%m-%d'), # 房屋创建时间
                'price': house.price,  # 房屋价格
                'area_name': house.area.name,  # 地区名字
                'address': house.address,  # 房屋地址
                'room_count': house.room_count,  # 房间数量
                'img_url': house.index_image_url,  # 房间图片
                'user_avatar': request.user.avatar_url  # 房屋所有者头像
            })
        # 构建前端数据格式
        data = {'total_page': num_pages, 'houses' : houses_list}
        data_dict = {'errno': RET.OK, 'errmsg': '请求成功', 'data': data}
        # 返回响应内容
        return http.JsonResponse(data_dict)








# 发布房源
class HouseView(LoginRequiredJSONMixin,View):
    def post(self,request):
        '''发布房源'''

        # 参
        json_dict = json.loads(request.body)
        title = json_dict.get('title')
        price = json_dict.get('price')
        area_id = json_dict.get('area_id')
        address = json_dict.get('address')
        room_count = json_dict.get('room_count')
        acreage = json_dict.get('acreage')
        unit = json_dict.get('unit')
        capacity = json_dict.get('capacity')
        beds = json_dict.get('beds')
        deposit = json_dict.get('deposit')
        min_days = json_dict.get('min_days')
        max_days = json_dict.get('max_days')

        facilities = json_dict.get('facility')


        # 校
        # 判全
        if not all([title,price,area_id,address,room_count,acreage,unit,capacity,beds,deposit,min_days,max_days,facilities]):
            return http.JsonResponse({'errno': RET.PARAMERR, 'errmsg': "参数有误"})


        # 判断城区
        try:
            area = Area.objects.get(id=area_id)
        except Exception as e:
            logger.error(e)
            return http.JsonResponse({'errno': RET.PARAMERR, 'errmsg': "参数有误"})

        # 修改金额
        try:
            price = int(float(price) * 100)
            deposit = int(float(deposit) * 100)
        except Exception as e:
            logger.error(e)
            return http.JsonResponse({'errno': RET.PARAMERR, 'errmsg': "参数有误"})
        # 业
        # 存入数据库

        try:
            house = House.objects.create(
                user = request.user,
                area = area,
                title = title,
                price = price,
                address = address,
                room_count = room_count,
                acreage = acreage,
                unit = unit,
                capacity = capacity,
                beds = beds,
                deposit = deposit,
                min_days = min_days,
                max_days = max_days,
            )
            house_facilitise = Facility.objects.filter(id__in=facilities)
            house.facilities.add(*house_facilitise)
            house.save()
        except Exception as e:
            print(e)

            return http.JsonResponse({'errno': RET.DATAERR, 'errmsg': "数据错误"})


        # 回
        return http.JsonResponse({'errno': RET.OK, 'errmsg': "Ok", 'data': {"house_id": house.pk}})


# 上传房源图片
class HouseImageView(LoginRequiredJSONMixin,View):
    def post(self,request,house_id):
        # 获取图片
        image = request.FILES.get('house_image')
        if image is None:
            return http.JsonResponse({'errno': RET.PARAMERR, 'errmsg': "参数错误"})

        # 上传图片　返回路径
        image_url = upload_img(image)
        if image_url is None:
            return http.JsonResponse({'errno': RET.PARAMERR, 'errmsg': "参数错误"})

        # 保存到数据库
        try:
            house_url = HouseImage.objects.create(
                url = image_url,
                house_id = house_id,
            )
            house_url.save()
            # 存默认图片
            house = House.objects.get(pk=house_id)
            house.index_image_url = image_url
            house.save()

        except Exception as e:
            logger.error(e)
            return http.JsonResponse({'errno': RET.DBERR , 'errmsg': "保存错误"})


        return http.JsonResponse({'errno': RET.OK, 'errmsg': "OK", 'data': {"url":image_url}})


# 我的房源
class GetHouseView(LoginRequiredJSONMixin,View):
    def get(self,request):
        '''我的房源'''
        # 参
        # 校
        # 业
        try:
            user = request.user
            houses = user.house_set.all()
        except Exception as e:
            logger.error(e)
            return http.JsonResponse({'errno': RET.DBERR, 'errmsg': "房信息查询失败"})

        # 构建数据格式
        data = []
        for house in houses:
            data.append({
                'address': house.address,
                'area_name': house.area.name,
                'ctime': house.create_time.strftime("%Y-%m-%d"),
                'house_id': house.pk,
                'img_url': house.index_image_url,
                'order_count': house.order_count,
                'price': house.price,
                'room_count': house.room_count,
                'title': house.title,
                'user_avatar': user.avatar_url,
            })

        # 回
        return http.JsonResponse({'errmsg': RET.OK, 'errno': '0', 'data': data})



